//
//  StringModifier.m
//  ZingBrowser
//
//  Created by -Xh- on 1/14/13.
//  Copyright (c) 2013 -Xh-. All rights reserved.
//

#import "StringModifier.h"

@implementation StringModifier


-(id)init{
    self= [super init];
    if(self){
        
    }
    return self;
}

-(NSString*)convertToGoogleSearchString:(NSString*)_inputString{
    
    NSString* googleSearchAPI=[NSString stringWithFormat:@"http://www.google.com/search?q="];
    NSString* resultString=[NSString stringWithFormat:@"%@%@",googleSearchAPI,_inputString];
    return resultString;
}

-(NSString*)addHTTPHeader:(NSString*)_inputString{
    NSString* httpString=[NSString stringWithFormat:@"http://"];
    int sameCount=0;
    for (int i=0;(i<_inputString.length && i<httpString.length); i++) {
        if([_inputString characterAtIndex:i] == [httpString characterAtIndex:i]){
            sameCount++;
        }else{
            break;
        }
    }
    if(sameCount>=5){
        _inputString=[_inputString substringFromIndex:sameCount];
    }
    
    return [NSString stringWithFormat:@"http://%@",_inputString];
}





-(NSString*)correctURL:(NSString *)_inputStringFromUser{
    //NSString* resultString=[NSString stringWithString:_inputStringFromUser];
    NSMutableArray* dotArray=[[NSMutableArray alloc]init];
    NSMutableArray* spaceArray=[[NSMutableArray alloc]init];
    if(_inputStringFromUser.length>=3){
        for(int i=1;i<_inputStringFromUser.length-1;i++){
            if([_inputStringFromUser characterAtIndex:i]=='.'){
                NSNumber* iValue=[NSNumber numberWithInt:i];
                [dotArray addObject:iValue];
            }
            if([_inputStringFromUser characterAtIndex:i]==' '){
                NSNumber* iValue=[NSNumber numberWithInt:i];
                [spaceArray addObject:iValue];
            }
        }
        if(dotArray.count==0 ){
            if(spaceArray.count!=0){             
                _inputStringFromUser=[_inputStringFromUser stringByReplacingOccurrencesOfString:@" " withString:@"+"];
            }
            return [self convertToGoogleSearchString:_inputStringFromUser];

        }
        int dotFirstIndex=[[dotArray objectAtIndex:0] intValue];
        if([_inputStringFromUser characterAtIndex:dotFirstIndex-1]=='w'
           || [_inputStringFromUser characterAtIndex:dotFirstIndex-1]=='W'){
            _inputStringFromUser=[_inputStringFromUser substringFromIndex:dotFirstIndex+1];
        }
        _inputStringFromUser=[_inputStringFromUser stringByReplacingOccurrencesOfString:@" " withString:@"+"];

        return [self addHTTPHeader:_inputStringFromUser];

        

    }else{
        return [self convertToGoogleSearchString:_inputStringFromUser];

    }
    
    
}
@end
